<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-form
        :inline="true"
        :model="formInline"
        class="demo-form-inline inputColorBlack"
      >
        <el-form-item label="商品名称">
          <el-input
            v-model="formInline.name"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品编号">
          <el-input
            v-model="formInline.goods_no"
            placeholder="请输入商品编号"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品类型">
          <el-cascader
            v-model="formInline.category_ids"
            :options="options"
            :props="{
              label: 'name',
              value: 'id',
              checkStrictly: true,
              emitPath: false,
            }"
            clearable
            class="wiIndex"
            @change="handleChange2"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商品品牌">
          <el-select
            v-model="formInline.brand_id"
            placeholder="请选择品牌"
            class="wiIndex"
            filterable
          >
            <el-option
              v-for="item in resUSer1"
              :key="item.index"
              :label="item.get_brand.name"
              :value="item.get_brand.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select v-model="formInline.is_del" placeholder="请选择是否上下架">
            <el-option label="上架" value="1"></el-option>
            <el-option label="下架" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品产地">
          <el-input
            v-model="formInline.origin"
            placeholder="请输入商品产地"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="onReset">重置</el-button>
          <el-button type="primary" @click="merchants">新增商品</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="text item">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        max-height="500"
      >
        <el-table-column align="center" label="商品ID" width="70" prop="id">
        </el-table-column>
        <el-table-column
          prop="name"
          align="center"
          label="商品名称"
          width="140"
        >
        </el-table-column>
        <el-table-column align="center" label="商品图片" width="100">
          <template slot-scope="scope">
            <el-image
              style="width: 80px; height: 80px"
              :src="imgHeader + scope.row.imgShow"
              fit="cover"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="color" align="center" label="商品颜色">
        </el-table-column>
        <el-table-column prop="goods_no" align="center" label="商品编号">
        </el-table-column>
        <el-table-column prop="categoryTS" align="center" label="商品类型">
        </el-table-column>
        <el-table-column prop="brand_id" align="center" label="商品品牌">
        </el-table-column>
        <el-table-column prop="store_nums" align="center" label="商品库存">
          <template slot-scope="scope">
            <span :style="scope.row.store_nums <= 50 ? 'color:red' : ''">{{
              scope.row.store_nums
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="商品详情"
          show-overflow-tooltip
          width="110"
        >
          <template slot-scope="scope">
            <el-image
              style="width: 80px; height: 80px"
              :src="imgHeader + scope.row.detail_chart.split(',')[0]"
              fit="cover"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="origin" align="center" label="商品产地">
        </el-table-column>
        <el-table-column
          prop="texture"
          align="center"
          label="商品材质"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column prop="model" align="center" label="商品型号">
        </el-table-column>
        <el-table-column prop="size" align="center" label="商品尺寸">
        </el-table-column>
        <el-table-column prop="weight" align="center" label="商品重量">
        </el-table-column>
        <el-table-column prop="unit" align="center" label="商品单位">
        </el-table-column>
        <el-table-column prop="sell_price" align="center" label="商品价格">
        </el-table-column>
        <el-table-column
          prop="is_del"
          align="center"
          label="商品状态"
          width="140"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_del"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="上架"
              inactive-text="下架"
              :active-value="0"
              :inactive-value="2"
              @change="switchChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" align="center" label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" @click="refuse(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 200, 300, 400]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="66%"
      :before-close="handleClose"
      :destory-on-close="true"
    >
      <span>
        <el-form
          ref="editDetail"
          :model="editDetail"
          :rules="rules"
          label-width="150px"
          :inline="true"
        >
          <div class="within">
            <el-form-item label="商品名称" prop="name">
              <el-input
                v-model="editDetail.name"
                placeholder="请输入商品名称"
                class="wiIndex"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品颜色" prop="color">
              <el-input
                v-model="editDetail.color"
                placeholder="请输入商品颜色"
                class="wiIndex"
              ></el-input>
            </el-form-item>
          </div>
          <div class="within">
            <el-form-item label="商品编号" prop="sell_price">
              <el-input
                placeholder="无需添加,自动生成"
                class="wiIndex"
                :disabled="true"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="weight">
              <div class="within">
                <el-input
                  v-model="editDetail.weight"
                  placeholder="请输入商品重量"
                  class="wiIndex"
                ></el-input>
                <div class="withinSpan">kg</div>
              </div>
            </el-form-item>
          </div>
          <div class="within goodsType">
            <el-form-item label="商品类型" prop="category_ids">
              <el-cascader
                v-model="editDetail.category_ids"
                :options="options"
                :props="{
                  label: 'name',
                  value: 'id',
                  checkStrictly: true,
                  emitPath: false,
                }"
                clearable
                class="wiIndex"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="商品品牌" prop="brand_id">
              <el-select
                v-model="editDetail.brand_id"
                placeholder="请选择品牌"
                class="wiIndex"
                filterable
              >
                <el-option
                  v-for="item in resUSer"
                  :key="item.index"
                  :label="item.get_brand.name"
                  :value="item.get_brand.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="within">
            <el-form-item label="商品库存" prop="store_nums">
              <el-input
                v-model="editDetail.store_nums"
                placeholder="请输入商品库存"
                class="wiIndex"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品产地" prop="origin">
              <el-input
                v-model="editDetail.origin"
                placeholder="请输入商品产地"
                class="wiIndex"
              ></el-input>
            </el-form-item>
          </div>
          <div class="within">
            <el-form-item label="商品材质" prop="texture">
              <el-input
                v-model="editDetail.texture"
                placeholder="请输入商品材质"
                class="wiIndex"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品型号" prop="model">
              <el-input
                v-model="editDetail.model"
                placeholder="请输入商品型号"
                class="wiIndex"
              ></el-input>
            </el-form-item>
          </div>
          <div class="within">
            <el-form-item label="商品尺寸" prop="size">
              <el-input
                v-model="editDetail.size"
                placeholder="请输入商品尺寸"
                class="wiIndex"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="sell_price">
              <el-input
                v-model="editDetail.sell_price"
                placeholder="请输入商品价格"
                class="wiIndex"
              ></el-input>
            </el-form-item>
          </div>
          <div class="within">
            <el-form-item label="商品单位" prop="unit">
              <el-input
                v-model="editDetail.unit"
                placeholder="请输入商品单位"
                class="wiIndex"
              ></el-input>
            </el-form-item>
            <el-form-item label="体积单位" prop="unit_val">
              <el-select v-model="editDetail.unit_val" placeholder="请选择">
                <el-option
                  v-for="item in unitOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- <div class="within" v-for="(item, index) in options1" :key="index">
            <el-form-item :label="item.title" collapse-tags prop="category_ids">
              <el-cascader
                v-model="item.name"
                :options="item.data"
                :props="{ label: 'name', value: 'name' }"
                clearable
                collapse-tags
                class="wiIndex"
              ></el-cascader>
            </el-form-item>
          </div> -->
          <el-form-item label="商品体积" required class="volume">
            <el-form-item prop="long"
              >长<el-input
                name=""
                id=""
                v-model="editDetail.long"
                class="input"
                :min="0"
                :max="10000"
              ></el-input
            ></el-form-item>
            x
            <!-- type="number" -->
            <el-form-item prop="width"
              >宽<el-input
                name=""
                id=""
                v-model="editDetail.width"
                class="input"
                :min="1"
                :max="10000"
                @change="handleChange1"
              ></el-input></el-form-item
            >x
            <el-form-item prop="height"
              >高<el-input
                name=""
                id=""
                v-model="editDetail.height"
                class="input"
                :min="0"
                :max="10000"
              ></el-input
            ></el-form-item>
          </el-form-item>
          <div class="within">
            <el-form-item label="是否可以裁断" prop="decide">
              <el-radio-group v-model="editDetail.decide" @change="radiochange">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <el-form-item label="商品图片">
            <el-upload
              class="upload-demo"
              action
              :http-request="uploadFiles"
              ref="upload"
              :limit="fileLimit"
              :on-remove="handleRemove"
              :file-list="fileList"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :headers="headers"
              multiple
              :on-change="fileChange"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过1M
              </div>
            </el-upload>
            <ul class="el-upload-list el-upload-list--picture-card">
              <draggable v-model="imgShowList">
                <li
                  v-for="(item, index) in imgShowList"
                  :key="index"
                  class="el-upload-list__item is-success animated"
                >
                  <img
                    :src="imgHeader + item"
                    alt=""
                    class="el-upload-list__item-thumbnail"
                  />
                  <i class="el-icon-close"></i>
                  <span class="el-upload-list__item-actions">
                    <!-- 预览 -->
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreviewFileDetail(item)"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <!-- 删除 -->
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleRemoveFileDetail(index)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </li>
              </draggable>
            </ul>
            <!-- <el-image
              v-for="(item1, index1) in imgShowList"
              :key="index1"
              class="imageGood"
              :src="'https://bjsf.bjsky.top/'+item1"
              style="width: 180px; height: 120px"
            ></el-image> -->
          </el-form-item>
          <el-form-item label="商品详情" class="wieHed">
            <!-- <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="editDetail.content"
            >
            </el-input> -->
            <el-upload
              class="upload-demo"
              action
              :http-request="uploadFiles1"
              ref="upload"
              :limit="fileLimit1"
              multiple
              :on-remove="handleRemove1"
              :file-list="fileList1"
              :on-exceed="handleExceed1"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :headers="headers"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过5M
              </div>
            </el-upload>
            <div class="imageBox">
              <ul class="el-upload-list el-upload-list--picture-card">
                <draggable v-model="imgShowList1">
                  <li
                    v-for="(item, index) in imgShowList1"
                    :key="index"
                    class="el-upload-list__item is-success animated"
                  >
                    <img
                      :src="imgHeader + item"
                      alt=""
                      class="el-upload-list__item-thumbnail"
                    />
                    <i class="el-icon-close"></i>
                    <span class="el-upload-list__item-actions">
                      <!-- 预览 -->
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreviewFileDetail(item)"
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <!-- 删除 -->
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleRemoveFileDetail1(index)"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </li>
                </draggable>
              </ul>
            </div>
          </el-form-item>
          <!-- <el-form-item label="购买须知" class="wieHed" prop="notice">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="editDetail.notice"
            >
            </el-input>
          </el-form-item> -->
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
    </el-dialog>
    <!-- 预览弹出层 -->
    <el-dialog :visible.sync="dialogVisibleDetail" class="imageDia">
      <el-image :src="imgHeader + dialogImageDetailUrl"></el-image>
    </el-dialog>
  </el-card>
</template>

<script>
import draggable from "vuedraggable";
import {
  uploadFiles,
  productList,
  additionSave,
  genreList,
  bindBrand,
  read,
  edit_status,
  edit_remove,
} from "../../../../utils/api";
import { getSelectList } from "../../../../utils/main";
import { compressImage } from "../../../../assets/js/compressImage";
export default {
  components: {
    draggable,
  },
  data() {
    var validatePass = (rule, value, callback) => {
      console.log(value);
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.editDetail.brand_id !== "") {
          this.$refs.editDetail.validateField("brand_id");
        }
        callback();
      }
    };
    return {
      serverUrl: "https://bjsf.bjsky.top/",
      loading: false,
      token: sessionStorage.getItem("token"),
      //弹框
      dialogVisible: false,
      //搜索数据
      formInline: {
        name: "",
        goods_no: "",
        brand_id: "",
        is_del: "",
        origin: "",
        category_ids: [],
      },
      selectList: [],
      category_id: "202",
      //列表展示
      tableData: [],
      //类型
      category_ids: [],
      imgShowList: [],
      imgShowList1: [],
      //新增
      editDetail: {
        name: "",
        color: "",
        brand_id: "",
        store_nums: "",
        origin: "",
        texture: "",
        model: "",
        weight: "",
        content: "",
        size: "",
        notice: "",
        sell_price: "",
        unit: "",
        category_ids: [],
        category_id1: [],
        //商家ID
        seller_id: 0,
        seller_shop_id: 0,
        long: 0,
        width: 0,
        height: 0,
        unit_val: "",
        decide: 0,
      },
      props: {
        multiple: true,
      },
      dialogImageDetailUrl: "",
      dialogVisibleDetail: false,
      //收集数据
      options1: [],
      options: [],
      unitOptions: [
        {
          value: "1",
          label: "mm",
        },
        {
          value: "2",
          label: "cm",
        },
        {
          value: "3",
          label: "m",
        },
      ],
      options1: [],
      resUSer1: [],
      resUSer: [],
      categoryS: "",
      //分页数据
      page: 1,
      limit: 10,
      total: 0,
      seller_shop_id: "",
      goods_id: "",
      //上传
      fileList: [],
      fileList1: [],
      fileType: ["png", "jpg", "jpeg"],
      fileLimit: 8,
      fileLimit1: 8,
      imgHeader: this.Global.imgHeader,

      headers: { "Content-Type": "multipart/form-data" },
      srcList2: {},
      rules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        color: [{ required: true, message: "请输入商品颜色", trigger: "blur" }],
        category_ids: [
          { required: true, message: "请选择商品类型", trigger: "change" },
        ],
        brand_id: [
          { required: true, message: "请选择商品品牌", trigger: "change" },
        ],
        store_nums: [
          { required: true, message: "请输入商品库存", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              var reg = /^\d+$/;
              if (!reg.test(value)) {
                callback(new Error("请输入不小于0的整数"));
              }
              // else if (value > 100000) {
              //   callback(new Error("不能大于100000"));
              // }
              else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        origin: [
          { required: true, message: "请输入商品产地", trigger: "blur" },
        ],
        texture: [
          { required: true, message: "请输入商品材质", trigger: "blur" },
        ],
        model: [{ required: true, message: "请输入商品型号", trigger: "blur" }],
        weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              var reg = /^(?!0+(?:\.0+)?$)(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;
              if (!reg.test(value)) {
                callback(new Error("请输入大于0且不超过两位小数的数字"));
              }
              // if (value > 99999999.99) {
              //   callback(new Error("不能大于99999999.99"));
              // }
              else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        size: [{ required: true, message: "请输入商品尺寸", trigger: "blur" }],
        content: [
          { required: true, message: "请输入商品详情", trigger: "blur" },
        ],
        notice: [
          { required: true, message: "请输入购买须知", trigger: "blur" },
        ],
        sell_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              var reg = /^(?!0+(?:\.0+)?$)(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;
              if (!reg.test(value)) {
                callback(new Error("请输入大于0且不超过两位小数的数字"));
              }
              // if (value > 99999999.99) {
              //   callback(new Error("不能大于99999999.99"));
              // }
              else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        unit_val: [
          { required: true, message: "请选择体积单位", trigger: "change" },
        ],
        unit: [{ required: true, message: "请输入商品单位", trigger: "blur" }],
        long: [
          { required: true, message: "请输入长", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              // var reg = /^(?!0+(?:\.0+)?$)(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;
              // if (!reg.test(value)) {
              //   callback(new Error("请输入大于0且不超过两位小数的数字"));
              // }
              if (Number.isNaN(Number(value))) {
                callback(new Error("请输入数字"));
              }
              if (value < 0) {
                callback(new Error("不能小于0"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        height: [
          { required: true, message: "请输入高", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              // var reg = /^(?!0+(?:\.0+)?$)(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;
              // if (!reg.test(value)) {
              //   callback(new Error("请输入大于0且不超过两位小数的数字"));
              // }
              // if (value > 99999999.99) {
              //   callback(new Error("不能大于99999999.99"));
              // }
              if (Number.isNaN(Number(value))) {
                callback(new Error("请输入数字"));
              }
              if (value < 0) {
                callback(new Error("不能小于0"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        width: [
          { required: true, message: "请输入宽", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              // var reg = /^(?!0+(?:\.0+)?$)(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;
              // if (!reg.test(value)) {
              //   callback(new Error("请输入大于0且不超过两位小数的数字"));
              // }
              // if (value > 99999999.99) {
              //   callback(new Error("不能大于99999999.99"));
              // }
              if (Number.isNaN(Number(value))) {
                callback(new Error("请输入数字"));
              }
              if (value < 0) {
                callback(new Error("不能小于0"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        decide: [
          { required: true, message: "请选择是否裁断", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    handleChange1(value) {
      console.log(value);
    },
    radiochange(e) {
      this.$forceUpdate();
    },
    // 删除详情图
    deletedetail_chartImage(e) {
      this.imgShowList1.splice(e, 1);
    },

    handlePictureCardPreviewFileDetail(file) {
      this.dialogImageDetailUrl = file;
      this.dialogVisibleDetail = true;
    },
    // 删除
    handleRemoveFileDetail(index) {
      this.imgShowList.splice(index, 1);
      this.fileList.splice(index, 1); //删除上传的文件
    },
    handleRemoveFileDetail1(index) {
      this.imgShowList1.splice(index, 1);
      this.fileList1.splice(index, 1); //删除上传的文件
    },
    //清空添加商品
    clearData() {
      this.editDetail.id = "";
      this.editDetail.name = "";
      this.editDetail.color = "";
      this.category_ids = [];
      this.editDetail.brand_id = "";
      this.editDetail.category_ids = "";
      this.editDetail.store_nums = "";
      this.editDetail.origin = "";
      this.editDetail.texture = "";
      this.editDetail.weight = "";
      this.editDetail.content = "";
      // this.editDetail.notice = "";
      this.editDetail.sell_price = "";
      this.editDetail.size = "";
      this.editDetail.model = "";
      this.editDetail.img = "";
      this.editDetail.unit = "";
      (this.editDetail.long = 0),
        (this.editDetail.width = 0),
        (this.editDetail.height = 0),
        (this.editDetail.decide = 0),
        (this.imgShowList = []);
      this.imgShowList1 = [];
    },
    //查询
    onSubmit() {
      this.page = 1;
      this.productLists();
    },
    //重置
    onReset() {
      (this.formInline.name = ""),
        (this.formInline.goods_no = ""),
        (this.formInline.brand_id = ""),
        (this.formInline.is_del = ""),
        (this.formInline.origin = ""),
        (this.formInline.category_ids = []),
        this.productLists();
    },
    // 搜索框获取筛选条件列表
    async getSelectList1(category_id) {
      // this.loading = true;
      let res = await getSelectList(this.token, category_id);
      if (res.data.status) {
        this.options1 = res.data.data.title_data || [];
        this.resUSer1 = res.data.data.brand_data;
        console.log("resUSer1", this.resUSer1);
      } else {
        if (res.data.msg == "token失效,请重新进行登录") {
          this.$router.push("/login");
        }
        if (res.data.msg == "此账号没有权限") {
          this.$message.error(res.data.msg);
          this.loading = false;
        }
      }
    },
    // 获取筛选条件列表
    async getSelectList() {
      // this.loading = true;
      let res = await getSelectList(this.token, this.category_id);
      if (res.data.status) {
        this.options1 = res.data.data.title_data || [];
        this.resUSer = res.data.data.brand_data;
      } else {
        if (res.data.msg == "token失效,请重新进行登录") {
          this.$router.push("/login");
        }
        if (res.data.msg == "此账号没有权限") {
          this.$message.error(res.data.msg);
          this.loading = false;
        }
      }
    },
    //新增商品
    merchants() {
      this.dialogVisible = true;
      // this.getSelectList();
    },
    //序号
    indexMethod(index) {
      if (this.token < this.limit) {
        return this.total - index;
      } else {
        return this.total - (this.page - 1) * this.limit - index;
      }
    },
    //编辑
    edit(row) {
      if (row.is_del == 0) {
        this.$message.warning("上架时不能编辑");
        return;
      }
      read(this.token, row.id).then((res) => {
        if (res.data.status) {
          this.dialogVisible = true;
          this.editDetail = res.data.data;
          let is_break = JSON.parse(JSON.stringify(this.editDetail)).is_break;
          //todo 删掉
          this.editDetail.category_ids = this.editDetail.show_categorys[0];
          this.getSelectList();
          // if (this.editDetail.category_ids) {
          //   if(this.editDetail.category_ids.length>=2){
          //     this.bindBrands(this.editDetail.category_ids[1]);
          //   }else{
          //     this.bindBrands(this.editDetail.category_ids[0]);
          //   }
          // }
          this.editDetail.long = this.editDetail.length;
          this.editDetail.decide = this.editDetail.is_break;
          // console.log( this.editDetail);

          if (this.editDetail.img) {
            const imgArr = this.editDetail.img.split(",");
            imgArr.forEach((img) => {
              this.imgShowList.push(img);
            });
          }
          if (this.editDetail.detail_chart) {
            const imgArr = this.editDetail.detail_chart.split(",");
            // console.log(imgArr);
            imgArr.forEach((img) => {
              this.imgShowList1.push(img);
            });
          }
        }
      });
    },
    //删除
    refuse(row) {
      if (row.is_del == 0) {
        this.$message.warning("上架时不能删除");
        return;
      }
      this.$confirm("确认删除选中商品吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          edit_remove(this.token, row.id).then((res) => {
            if (res.data.status) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.productLists();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //列表商品状态
    switchChange(row) {
      edit_status(this.token, row.id, row.is_del)
        .then((res) => {
          if (res.data.status) {
            this.productLists();
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
            if (res.data.msg == "此账号没有权限") {
              this.$message.error(res.data.msg);
              this.loading = false;
            }
            let timer = setTimeout(() => {
              this.$message.error(res.data.msg);
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    //分页器
    handleSizeChange(val) {
      this.limit = val;

      this.productLists();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.productLists();
    },
    //关闭弹框
    handleClose(done) {
      done();
      this.$refs.editDetail.resetFields();
      this.clearData();
    },
    //保存
    save() {
      this.editDetail.detail_chart = "";
      this.editDetail.img = "";
      this.imgShowList1.forEach((item) => {
        this.editDetail.detail_chart += item + ",";
      });
      this.imgShowList.forEach((item) => {
        this.editDetail.img += item + ",";
      });
      this.editDetail.img = this.editDetail.img.slice(0, -1);
      this.editDetail.detail_chart = this.editDetail.detail_chart.slice(0, -1);
      this.$refs["editDetail"].validate((valid) => {
        if (valid) {
          if (this.editDetail.img) {
            console.log(this.editDetail);
            this.additionSaves();
          } else {
            this.$message({
              message: "请上传图片",
              type: "warning",
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    cancel() {
      this.$refs.editDetail.resetFields();
      this.dialogVisible = false;
    },
    //上传
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    handleExceed1() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //这是我自定义的移除事件
    handleClosedelete(i) {
      // this.fileList.splice(i, 1);//删除上传的文件
    },
    //上传文件的格式
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制

        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          // console.log("上传前", file);

          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    fileChange(file, fileList) {
      this.fileList = fileList;
      // console.log("fileList", this.fileList);
    },
    // 压缩文件
    async compressFile(singleFile) {
      let config = {
        quality: 0.5, //默认0.5  0-1
        // width:100,
        // height:100
      };
      let result = await compressImage({
        file: singleFile.raw,
        config,
        fileName: singleFile.name,
      });
      this.srcList2 = result.finalFile;
      console.log("bbb", this.srcList2);
      // console.log("压缩后图片1===>", this.imageList);
    },
    // 上传文件的事件
    async uploadFiles(item) {
      // console.log("item1", item);
      this.$message("文件上传中........");
      let singleFile = {};
      singleFile.raw = item.file;
      singleFile.name = item.file.name;
      singleFile.size = item.file.size;
      singleFile.uid = item.file.uid;
      await this.compressFile(singleFile);
      console.log("srcList2", this.srcList2);
      uploadFiles(this.srcList2).then((res) => {
        if (res.data.status != false || res.data.id != null) {
          res.data.data.saveurl; //半截
          res.data.data.weburl; //全拼
          this.imgShowList.push(res.data.data.saveurl);
          // this.fileList.push(this.srcList2); //成功过后手动将文件添加到展示列表里
          // let i = this.fileList.indexOf(this.srcList2);
          this.handleSuccess();
        }
      });
      //上传文件的需要formdata类型;所以要转
      // uploadFiles(item.file).then((res) => {
      //   if (res.data.status != false || res.data.id != null) {
      //     res.data.data.saveurl; //半截
      //     res.data.data.weburl; //全拼
      //     this.imgShowList.push(res.data.data.saveurl);
      //     this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
      //     // let i = this.fileList.indexOf(item.file);
      //     this.handleSuccess();
      //   }
      // });
    },
    async uploadFiles1(item) {
      console.log("item", item);
      let singleFile = {};
      singleFile.raw = item.file;
      singleFile.name = item.file.name;
      singleFile.size = item.file.size;
      singleFile.uid = item.file.uid;
      await this.compressFile(singleFile);
      // console.log("srcList2", this.srcList2);
      uploadFiles(this.srcList2).then((res) => {
        if (res.data.status != false || res.data.id != null) {
          res.data.data.saveurl; //半截
          res.data.data.weburl; //全拼
          this.imgShowList1.push(res.data.data.saveurl);
          // this.fileList.push(this.srcList2); //成功过后手动将文件添加到展示列表里
          // let i = this.fileList.indexOf(this.srcList2);
          this.handleSuccess();
        }
      });
      // uploadFiles(item.file).then((res) => {
      //   res.data.data.saveurl; //半截
      //   res.data.data.weburl; //全拼
      //   console.log(res);
      //   this.imgShowList1.push(res.data.data.saveurl);
      //   console.log(this.editDetail);
      //   this.fileList1.push(item.file); //成功过后手动将文件添加到展示列表里
      //   console.log("上传后文件2", this.fileList1);
      //   let i = this.fileList.indexOf(item.file);
      //   this.handleSuccess();
      // });
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClosedelete();
    },
    //新增员工
    handleRemove() {},
    handleRemove1() {},
    //商品列表展示
    productLists() {
      this.loading = true;
      productList(
        this.token,
        this.formInline.name,
        this.formInline.goods_no,
        this.formInline.brand_id,
        this.formInline.is_del,
        this.formInline.origin,
        this.formInline.category_ids,
        this.seller_shop_id,
        this.goods_id,
        this.page,
        this.limit,
        "",
        1
      )
        .then((res) => {
          if (res.data.status) {
            this.tableData = res.data.data.data;
            this.total = res.data.data.total;
            this.tableData.forEach((item) => {
              if (item.brand) {
                item.brand_id = item.brand.name;
              }
              if (item.img) {
                item.imgShow = item.img.split(",")[0];
                // console.log(item.img.split(",")[0]);
                // console.log(item.img.split(","));
              }
              // console.log(item);
              item.categorys.forEach((item1) => {
                if (item1.category != null) {
                  this.categoryS = item1.category;
                  item.categoryTS = this.categoryS.name;
                }
              });
            });
            let timer = setTimeout(() => {
              this.loading = false;
              clearTimeout(timer);
            }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
            if (res.data.msg == "此账号没有权限") {
              this.$message.error(res.data.msg);
              this.loading = false;
            }
            let timer = setTimeout(() => {
              this.$message.error(res.data.msg);
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    //商品添加
    additionSaves() {
      console.log(this.editDetail);
      additionSave(
        this.token,
        this.editDetail.id,
        this.editDetail.name,
        this.editDetail.color,
        this.editDetail.brand_id,
        this.editDetail.store_nums,
        this.editDetail.origin,
        this.editDetail.texture,
        this.editDetail.model,
        this.editDetail.weight,
        this.editDetail.size,
        this.editDetail.content,
        "购买须知",
        this.editDetail.sell_price,
        this.editDetail.category_ids,
        this.editDetail.img,
        this.editDetail.unit,
        this.editDetail.seller_shop_id,
        this.editDetail.seller_id,
        this.editDetail.unit_val,
        this.editDetail.long,
        this.editDetail.width,
        this.editDetail.height,
        this.editDetail.decide, //是否截断
        this.editDetail.detail_chart //图片
      ).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.clearData();
          this.dialogVisible = false;
          this.$refs.editDetail.resetFields();

          this.productLists();
        } else {
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
            let timer = setTimeout(() => {
              this.$message.error("错误，请刷新");
            }, 5000);
          }
          this.$message.error(res.data.msg);
          this.dialogVisible = false;
          this.$refs.editDetail.resetFields();
          this.productLists();
        }
      });
    },

    //获取分类数据数据
    genreLists() {
      genreList(this.token)
        .then((res) => {
          if (res.data.status) {
            this.options1 = res.data.data;
            this.options1 = this.options1.filter(function (item) {
              return item.id == 35;
            });
            this.options = this.options1[0].children;
            console.log(this.options);
            let timer = setTimeout(() => {
              clearTimeout(timer);
            }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
            if (res.data.msg == "此账号没有权限") {
              this.$message.error(res.data.msg);
            }
            let timer = setTimeout(() => {
              this.$message.error(res.data.msg);
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    // 搜索时选择商品类型
    handleChange2() {
      // this.resUSer = [];
      // this.formInline.category_ids = "";
      this.formInline.brand_id = "";
      let category_id = this.formInline.category_ids;
      this.getSelectList1(category_id);
    },
    // 新增商品选择商品类型
    handleChange(e) {
      console.log(e);
      // this.resUSer = [];
      this.editDetail.brand_id = "";
      this.category_id = this.editDetail.category_ids;
      this.getSelectList();
    },
    // handleChange1() {},
    //品牌
    bindBrands(id) {
      this.loading = true;
      this.resUSer = [];
      //   bindBrand(id)
      //     .then((res) => {
      //       if (res.data.status) {
      //         let resUSer = res.data.data.brand_list;
      //         console.log(resUSer);
      //         if (resUSer != null) {
      //           resUSer.forEach((item) => {
      //             if (item.get_brand != null) {
      //               this.resUSer.push(item.get_brand);
      //             }
      //           });
      //         }
      //         let timer = setTimeout(() => {
      //           this.loading = false;
      //           clearTimeout(timer);
      //         }, 400);
      //       } else {
      //         if (res.data.msg == "token失效,请重新进行登录") {
      //           this.$router.push("/login");
      //         }
      //         if (res.data.msg == "此账号没有权限") {
      //           this.$message.error(res.data.msg);
      //           this.loading = false;
      //         }
      //         let timer = setTimeout(() => {
      //           this.$message.error(res.data.msg);
      //         }, 5000);
      //       }
      //     })
      //     .catch((err) => {
      //       console.log(err.message);
      //     });
    },
  },
  mounted() {
    this.productLists();
    this.genreLists();
  },
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

.within {
  width: 100%;
  display: flex;
  flex-wrap: nowrap;
}

.within .el-form-item {
  width: 45%;
}

.typeface {
  margin-left: 10px;
  margin-top: 9px;
}

.withinSpan {
  margin-left: 5px;
  width: 21px;
}

.he {
  margin-right: 155px;
  width: 300px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.imageGood {
  margin: 0 10px;
  position: relative;
}

.goodsType {
  display: flex;
  flex-wrap: wrap;
}

.wieHed {
  width: 100%;
}

.volume .el-form-item__content {
  display: flex;
}
.volume .el-form-item__content .el-form-item {
  margin: 0 10px;
}
.volume .el-form-item__content .el-form-item .el-form-item__content {
  display: flex;
  margin-bottom: 10px;
}
.volume .el-form-item__content .el-form-item .el-form-item__content .input {
  width: 100px;
  margin-left: 20px;
}
.imageBox {
  widows: 90%;
  display: flex;
  flex-wrap: wrap;
}
.imageBox .imageInner {
  position: relative;
}
.imgDelete {
  position: absolute;
  left: 50%;
  bottom: 15px;
  width: 180px;
  text-align: center;
  background: rgba(108, 112, 117, 0.5);
  transform: translate(-50%, -0%);
  cursor: pointer;
}
.imageDia {
}
.imageDia .el-dialog {
}
.imageDia .el-dialog__body {
  display: flex;
  align-items: center;
  justify-content: center;
}
.upload-demo .el-upload--text {
  border: none;
  width: auto;
  height: auto;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>
